package com.qf.blog.commons.utils;

import com.qf.blog.dto.EmailDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
public class EmailUtils {

    @Autowired
    private JavaMailSender javaMailSender;
    @Value(value = "${spring.mail.username}")
    private String fromEmail;


    public void sendEmail(EmailDto email) {

        // 1.创建有一个邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        try {
            // 2.创建一个发送邮件的帮助类
            MimeMessageHelper helper= new MimeMessageHelper(mimeMessage, true);

            helper.setTo(email.getTo()); // 收件人
            helper.setSubject(email.getTitle()); // 标题
            helper.setText(email.getContent(),true); // 内容
            helper.setFrom(fromEmail); // 发件人

            javaMailSender.send(mimeMessage); // 发送
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
